package cn.wenhaha.install.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.db.ds.simple.SimpleDataSource;
import cn.hutool.db.sql.SqlExecutor;
import cn.wenhaha.common.utils.ScriptRunner;
import cn.wenhaha.common.utils.YamlUtils;
import cn.wenhaha.install.service.InstallSqlScript;

import javax.sql.DataSource;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.util.HashMap;

public class MysqlInstallScript implements InstallSqlScript {



    @Override
    public void execute(YamlUtils yamlUtils) throws Exception {
        //执行sql文件
        InputStream inputStream =  null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("sql/mysql/install.sql");
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("安装sql文件丢失!");
        }

        String jdbcUrl = (String)yamlUtils.getByKey("datasource.link");
        String username = (String)yamlUtils.getByKey("datasource.username");
        String password = (String)yamlUtils.getByKey("datasource.password");

        DataSource ds = new SimpleDataSource(jdbcUrl,username, password);
        try( Connection connection = ds.getConnection()){

            ScriptRunner runner = new ScriptRunner(connection);
            runner.setFullLineDelimiter(false);
            runner.setDelimiter(";");//语句结束符号设置
            runner.setLogWriter(null);//日志数据输出，这样就不会输出过程
            runner.setSendFullScript(false);
            runner.setAutoCommit(true);
            runner.setStopOnError(true);
            runner.runScript(new InputStreamReader(inputStream, "utf8"));
            //插入管理员账号密码
            String name= (String)yamlUtils.getByKey("app.admin.name");
            String pwd= (String)yamlUtils.getByKey("app.admin.pwd");
            String salt= RandomUtil.randomString(4);
            String sql="INSERT INTO `sys_user`(`user_id`, `login_name`, `user_name`, `user_type`, `avatar`, `password`, `salt`, `status`, `del_flag`, `login_ip`, `create_by`,  `update_by`, `remark`,`create_time`,`update_time`,`role_code`,`role_name`) VALUES" +
                    " (1, ?, '管理员', '00', '{avatar}', '{pwd}', '{salt}', '0', '0', '', '系统', '系统',  '管理员','{createTime}','{createTime}','{roleCode}','{roleName}')";
            pwd = SecureUtil.md5(pwd + salt);
            HashMap<String, String> dataMap = new HashMap<>(3);
            dataMap.put("pwd",pwd);
            dataMap.put("roleCode","admin");
            dataMap.put("roleName","管理员");
            dataMap.put("salt",salt);
            dataMap.put("createTime", DateUtil.now());
            dataMap.put("avatar","https://i.328888.xyz/2023/01/23/OJSfJ.th.png");
            int execute = SqlExecutor.execute(connection, StrUtil.format(sql,dataMap),name);
            if (execute!=1){
                throw new Exception("管理员账号设置失败");
            }
        }


    }
}
